package com.tinem.platform.service.robot.im.adaptation.hjxc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.service.robot.im.core.Message;
import com.tinem.platform.service.robot.im.core.UserService;
import com.tinem.platform.service.robot.im.jpa.entity.RbacUserMapping;
import jakarta.annotation.Resource;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class OnMessage {

    private static final Logger log = LoggerFactory.getLogger(OnMessage.class);

    @Value("${spring.profiles.active}")
    protected String active;
    @Resource
    HjxcAutoProperties hjxcAutoProperties;

    @Value("${INSTANCE_NAME}")
    String clientId;

    @Resource
    Api api;

    @Resource
    UserService userService;
    @Autowired
    private ApplicationContext applicationContext;

    public void onMessage() throws MqttException {
        String subTopic = (active.equals("dev")?"test":active)+"/platform/message/user/"+api.userInfo.getString("id")+"/";
        int qos = 2;
        String broker = "tcp://"+hjxcAutoProperties.mqtt()+":1883";
        MemoryPersistence persistence = new MemoryPersistence();

        MqttClient client = new MqttClient(broker, clientId, persistence);

        // MQTT 连接选项
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName(api.userInfo.getString("id"));
        connOpts.setPassword(api.access_token.toCharArray());
        // 保留会话
        connOpts.setCleanSession(true);

        // 设置回调
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable throwable) {

            }

            @Override
            public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                String s = new String(mqttMessage.getPayload());
                JSONObject message = JSON.parseObject(s);
                JSONObject req = message.getJSONObject("req");
                if(!req.getString("messageType").equals("msg_txt")){
                    return;
                }if(req.getString("fromId").equals(api.userInfo.getString("id"))){
                    return;
                }
                RbacUserMapping fromUser = userService.getUserId(hjxcAutoProperties.clientId(),req.getString("fromId"));
                Message msg = new Message(fromUser,req.getString("content"),hjxcAutoProperties.clientId(),message.getString("client_msg_id"));
                applicationContext.publishEvent(msg);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });
        client.connect(connOpts);
        client.subscribe(subTopic,qos);

    }
}
